package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.pojo.TransferOrder;
import com.zhentao.service.TransferOrderService;
import com.zhentao.util.ExcelExportUtil;
import com.zhentao.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 转账单管理接口
 */
@RestController
@RequestMapping("/finance/transferOrder")
public class TransferOrderController {

    @Autowired
    private TransferOrderService transferOrderService;

    /**
     * 分页查询转账单
     */
    @GetMapping("/list")
    public Result<Page<TransferOrder>> list(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Long fromWarehouseId,
            @RequestParam(required = false) Long toWarehouseId,
            @RequestParam(required = false) String transferNo,
            @RequestParam(required = false) Long tenantId) {
        
        try {
            Page<TransferOrder> page = new Page<>(current, size);
            QueryWrapper<TransferOrder> wrapper = new QueryWrapper<>();
            
            if (status != null) {
                wrapper.eq("status", status);
            }
            if (fromWarehouseId != null) {
                wrapper.eq("from_warehouse_id", fromWarehouseId);
            }
            if (toWarehouseId != null) {
                wrapper.eq("to_warehouse_id", toWarehouseId);
            }
            if (StringUtils.hasText(transferNo)) {
                wrapper.like("transfer_no", transferNo);
            }
            if (tenantId != null) {
                wrapper.eq("tenant_id", tenantId);
            }
            wrapper.orderByDesc("create_time");
            
            IPage<TransferOrder> result = transferOrderService.page(page, wrapper);
            return Result.success((Page<TransferOrder>) result);
        } catch (Exception e) {
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 根据ID查询转账单
     */
    @GetMapping("/{id}")
    public Result<TransferOrder> getById(@PathVariable Long id) {
        try {
            TransferOrder transferOrder = transferOrderService.getById(id);
            if (transferOrder != null) {
                return Result.success(transferOrder);
            } else {
                return Result.error("转账单不存在");
            }
        } catch (Exception e) {
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 新增转账单
     */
    @PostMapping("/add")
    public Result<String> add(@RequestBody TransferOrder transferOrder) {
        try {
            if (transferOrder.getCreateTime() == null) {
                transferOrder.setCreateTime(new Date());
            }
            if (transferOrder.getStatus() == null) {
                transferOrder.setStatus(0); // 0-待审核
            }
            if (transferOrder.getTenantId() == null) {
                transferOrder.setTenantId(1L);
            }
            
            boolean success = transferOrderService.save(transferOrder);
            if (success) {
                return Result.success("新增成功");
            } else {
                return Result.error("新增失败");
            }
        } catch (Exception e) {
            return Result.error("新增失败：" + e.getMessage());
        }
    }

    /**
     * 修改转账单
     */
    @PutMapping("/update")
    public Result<String> update(@RequestBody TransferOrder transferOrder) {
        try {
            boolean success = transferOrderService.updateById(transferOrder);
            if (success) {
                return Result.success("修改成功");
            } else {
                return Result.error("修改失败");
            }
        } catch (Exception e) {
            return Result.error("修改失败：" + e.getMessage());
        }
    }

    /**
     * 删除转账单
     */
    @DeleteMapping("/{id}")
    public Result<String> delete(@PathVariable Long id) {
        try {
            boolean success = transferOrderService.removeById(id);
            if (success) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            return Result.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 批量删除转账单
     */
    @PostMapping("/batchDelete")
    public Result<String> batchDelete(@RequestBody List<Long> ids) {
        try {
            boolean success = transferOrderService.removeByIds(ids);
            if (success) {
                return Result.success("批量删除成功");
            } else {
                return Result.error("批量删除失败");
            }
        } catch (Exception e) {
            return Result.error("批量删除失败：" + e.getMessage());
        }
    }

    /**
     * 审核转账单
     */
    @PostMapping("/approve/{id}")
    public Result<String> approve(@PathVariable Long id) {
        try {
            TransferOrder transferOrder = transferOrderService.getById(id);
            if (transferOrder == null) {
                return Result.error("转账单不存在");
            }
            
            transferOrder.setStatus(1); // 设置为已审核
            boolean success = transferOrderService.updateById(transferOrder);
            if (success) {
                return Result.success("审核成功");
            } else {
                return Result.error("审核失败");
            }
        } catch (Exception e) {
            return Result.error("审核失败：" + e.getMessage());
        }
    }

    /**
     * 批量审核转账单
     */
    @PostMapping("/batchApprove")
    public Result<String> batchApprove(@RequestBody List<Long> ids) {
        try {
            List<TransferOrder> transferOrders = new ArrayList<>();
            for (Long id : ids) {
                TransferOrder transferOrder = new TransferOrder();
                transferOrder.setId(id);
                transferOrder.setStatus(1); // 设置为已审核
                transferOrders.add(transferOrder);
            }
            
            boolean success = transferOrderService.updateBatchById(transferOrders);
            if (success) {
                return Result.success("批量审核成功");
            } else {
                return Result.error("批量审核失败");
            }
        } catch (Exception e) {
            return Result.error("批量审核失败：" + e.getMessage());
        }
    }

    /**
     * 获取统计数据
     */
    @GetMapping("/stats")
    public Result<Object> getStats() {
        try {
            QueryWrapper<TransferOrder> wrapper = new QueryWrapper<>();
            
            List<TransferOrder> transferOrders = transferOrderService.list(wrapper);
            
            int totalCount = transferOrders.size();
            int approvedCount = 0;
            int pendingCount = 0;
            
            // 统计各状态数量
            for (TransferOrder order : transferOrders) {
                if (order.getStatus() != null) {
                    if (order.getStatus() == 1) {
                        approvedCount++;
                    } else if (order.getStatus() == 0) {
                        pendingCount++;
                    }
                }
            }
            
            java.util.Map<String, Object> stats = new java.util.HashMap<>();
            stats.put("totalCount", totalCount);
            stats.put("approvedCount", approvedCount);
            stats.put("pendingCount", pendingCount);
            
            return Result.success(stats);
        } catch (Exception e) {
            return Result.error("获取统计数据失败：" + e.getMessage());
        }
    }

    /**
     * 导出转账单数据
     */
    @GetMapping("/export")
    public void export(TransferOrder query, HttpServletResponse response) throws IOException {
        try {
            QueryWrapper<TransferOrder> wrapper = new QueryWrapper<>();
            
            if (query != null) {
                if (query.getStatus() != null) {
                    wrapper.eq("status", query.getStatus());
                }
                if (query.getFromWarehouseId() != null) {
                    wrapper.eq("from_warehouse_id", query.getFromWarehouseId());
                }
                if (query.getToWarehouseId() != null) {
                    wrapper.eq("to_warehouse_id", query.getToWarehouseId());
                }
                if (StringUtils.hasText(query.getTransferNo())) {
                    wrapper.like("transfer_no", query.getTransferNo());
                }
                if (query.getTenantId() != null) {
                    wrapper.eq("tenant_id", query.getTenantId());
                }
            }
            wrapper.orderByDesc("create_time");
            
            // 查询所有数据
            List<TransferOrder> transferOrders = transferOrderService.list(wrapper);
            
            // 准备Excel数据
            List<String> headers = new ArrayList<>();
            headers.add("转账单号");
            headers.add("来源仓库");
            headers.add("目标仓库");
            headers.add("状态");
            headers.add("创建时间");
            
            List<List<Object>> dataList = new ArrayList<>();
            for (TransferOrder order : transferOrders) {
                List<Object> row = new ArrayList<>();
                row.add(order.getTransferNo() != null ? order.getTransferNo() : "");
                row.add(order.getFromWarehouseId() != null ? order.getFromWarehouseId().toString() : "");
                row.add(order.getToWarehouseId() != null ? order.getToWarehouseId().toString() : "");
                row.add(getStatusText(order.getStatus()));
                row.add(order.getCreateTime() != null ? order.getCreateTime().toString() : "");
                dataList.add(row);
            }
            
            // 导出Excel
            String fileName = "转账订单数据_" + java.time.LocalDate.now();
            ExcelExportUtil.exportToResponse(response, fileName, headers, dataList);
            
        } catch (Exception e) {
            // 如果导出失败，返回错误信息
            response.reset();
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write("导出失败：" + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 获取状态文本
     */
    private String getStatusText(Integer status) {
        if (status == null) return "";
        switch (status) {
            case 0: return "待审核";
            case 1: return "已审核";
            case 2: return "已拒绝";
            default: return "未知";
        }
    }
}
